/*	******************************************
	File:		HaarTracker.cpp
	Author:		Adnan Srna, Peter Kober, Ivo Havranek
	Purpose:	AugmentedReality 2
	(up)Date:	March/April 2010
	Descr.:		function for face tracking 
	Origin:		Salzburg University of Applied Science
	******************************************	*/

#include "HaarTracker.h"

void CHaar::setup(){
	vidGrabber.setVerbose(true);
	vidGrabber.initGrabber(WIDTH, HEIGHT);

	colorLargeImage.allocate(WIDTH, HEIGHT);
	colorSmallImage.allocate(SAMPLE_WIDTH, SAMPLE_HEIGHT);
    grayLargeImage.allocate(WIDTH, HEIGHT);
	graySmallImage.allocate(SAMPLE_WIDTH, SAMPLE_HEIGHT);
	
	sourceToSampleScale = WIDTH / SAMPLE_WIDTH;
	sampleToSourceScale	= SAMPLE_WIDTH / (float)WIDTH;

	//haarFinder.setup("haarcascades/haarcascade_frontalface_default.xml");
	haarFinder.setup("haarcascades/haarcascade_mcs_mouth.xml");
	//haarFinder.setup("haarcascades/haarcascade_eye.xml");

	haarTracker.setup(&haarFinder);

	amplitude = 160;
}

void CHaar::update(){
	bool bNewFrame = false;
	vidGrabber.grabFrame();
	bNewFrame = vidGrabber.isFrameNew();
	
	if(bNewFrame)
	{
		colorLargeImage.setFromPixels(vidGrabber.getPixels(), WIDTH, HEIGHT);
		colorLargeImage.mirror(false, true);
		colorSmallImage.scaleIntoMe(colorLargeImage);
		
		grayLargeImage	= colorLargeImage;
		graySmallImage	= colorSmallImage;
		
		haarTracker.findHaarObjects(graySmallImage);
	}
}

void CHaar::draw(){
	ofBackground(250, 0, 0);
	int i, faceID;
	float wRatio, hRatio, scale;
	float faceMode;
	
	wRatio = ofGetWidth() / (float)WIDTH;
	hRatio = ofGetHeight() / (float)HEIGHT;

	scale = MIN(wRatio, hRatio);
	
	glPushMatrix();
	glTranslatef(
		(int)((ofGetWidth() - (WIDTH * scale)) * 0.5f),
		(int)((ofGetHeight() - (HEIGHT * scale)) * 0.5f),
		0
	);
	glScalef(scale, scale, 0);
	
	ofSetColor(0xffffff);
	grayLargeImage.draw(0, 0);

	while(haarTracker.hasNextHaarItem())
	{
		faceID		= haarTracker.getHaarItemID();
		faceMode	= 1;
		
		haarTracker.getHaarItemPropertiesEased(&x, &y, &w, &h);
		
		x	*= sourceToSampleScale;
		y	*= sourceToSampleScale;
		w	*= sourceToSampleScale;
		h	*= sourceToSampleScale;
		
		_pos.x = x;
		_pos.y = y;
		amplitude = x + w/2;

		/*if(faceMode > 0.66)			ofSetColor(0xFF0000);
		else if(faceMode > 0.33)	ofSetColor(0x00FF00);
		else						ofSetColor(0x0000FF);*/
		
		ofNoFill();
		ofSetLineWidth(3);
		ofSetColor(0, 0, 255);
		ofRect(x, y, w, h);
		glPopMatrix();
		ofSetColor(255, 255, 255);
	}
}
